package com.ibeeking.found.cop.b.rest.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.enums.DefaultEnum;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.enums.SyncStatusEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.cop.b.rest.service.ICopAttachementService;
import com.ibeeking.found.cop.b.rest.service.IKfWikiService;
import com.ibeeking.found.cop.service.common.dos.KfWikiDO;
import com.ibeeking.found.cop.service.common.param.CopAttachementParam;
import com.ibeeking.found.cop.service.common.param.KfWikiParam;
import com.ibeeking.found.cop.service.common.param.UniAttachParam;
import com.ibeeking.found.cop.service.common.query.CopAttachementQuery;
import com.ibeeking.found.cop.service.common.query.KfWikiPageQuery;
import com.ibeeking.found.cop.service.common.query.KfWikiQuery;
import com.ibeeking.found.cop.service.common.vo.CopAttachementVO;
import com.ibeeking.found.cop.service.common.vo.KfWikiVO;
import com.ibeeking.found.cop.service.common.vo.UniAttachVO;
import com.ibeeking.found.cop.service.mapper.KfWikiMapper;
import com.ibeeking.found.id.GenerateId;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName KfWikiServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class KfWikiServiceImpl extends ServiceImpl<KfWikiMapper, KfWikiDO> implements IKfWikiService {

    @Resource
    private KfWikiMapper kfWikiMapper;

    @Resource
    private ICopAttachementService copAttachementServiceImpl;

    @Override
    public List<KfWikiVO> list(KfWikiQuery query) {
        List<KfWikiDO> entityDOS = kfWikiMapper.selectList(new LambdaQueryWrapper<KfWikiDO>()
                .eq(query.getId() != null, KfWikiDO::getId, query.getId())
                .eq(query.getGroupId() != null, KfWikiDO::getGroupId, query.getGroupId())
                .eq(query.getMarkCommon() != null, KfWikiDO::getMarkCommon, query.getMarkCommon())
                .like(StringUtils.isNotBlank(query.getName()), KfWikiDO::getName, query.getName())
                .like(StringUtils.isNotBlank(query.getContent()), KfWikiDO::getContent, query.getContent())
                .eq(query.getStatus() != null, KfWikiDO::getStatus, query.getStatus())
                .orderByDesc(KfWikiDO::getCreateTime)
        );
        List<KfWikiVO> entityVOS =JsonUtils.jsonToList(entityDOS, KfWikiVO.class);
        if(Collections3.isNotEmpty(entityVOS)) {
            List<Long> ids = entityVOS.stream().map(KfWikiVO::getId).collect(Collectors.toList());
            CopAttachementQuery attachementQuery = new CopAttachementQuery();
            attachementQuery.setMessageIds(ids);
            List<CopAttachementVO> copAttachementVOS = copAttachementServiceImpl.list(attachementQuery);
            Map<Long, CopAttachementVO> copAttachementMap = Collections3.isNotEmpty(copAttachementVOS)?copAttachementVOS.stream().collect(Collectors.toMap(CopAttachementVO::getMessageId, x->x, (o, n) -> n)):null;

            entityVOS.forEach(x -> {
                x.setMarkCommonName(DefaultEnum.getDescByValue(x.getMarkCommon()));
                x.setStatusDesc(PublishStatusEnum.getName(x.getStatus()));
                x.setSyncStatusDesc(SyncStatusEnum.getName(x.getSyncStatus()));
                CopAttachementVO copAttachementVO = copAttachementMap!=null && copAttachementMap.size()>0?copAttachementMap.get(x.getId()):null;
                if(copAttachementVO!=null){
                    List<UniAttachVO> uniAttachVOS = copAttachementServiceImpl.transerCopAttachementToUniAttachement(copAttachementVO);
                    x.setAttachements(uniAttachVOS);
                }
            });
        }
        return entityVOS;
    }

    @Override
    public Page<KfWikiVO> pageList(KfWikiPageQuery pageQuery) {
        LambdaQueryWrapper<KfWikiDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(pageQuery.getId() != null, KfWikiDO::getId, pageQuery.getId())
                .eq(pageQuery.getGroupId() != null, KfWikiDO::getGroupId, pageQuery.getGroupId())
                .like(StringUtils.isNotBlank(pageQuery.getName()), KfWikiDO::getName, pageQuery.getName())
                .like(StringUtils.isNotBlank(pageQuery.getContent()), KfWikiDO::getContent, pageQuery.getContent())
                .eq(pageQuery.getStatus() != null, KfWikiDO::getStatus, pageQuery.getStatus())
                .orderByDesc(KfWikiDO::getCreateTime);
        Page<KfWikiDO> entityDOPages = kfWikiMapper.selectPage(new Page<KfWikiDO>(pageQuery.getPageNum(), pageQuery.getPageSize()), wrapper);
        Page<KfWikiVO> entityVOPages = BeanUtil.convertPage(entityDOPages, KfWikiVO.class);
        if(entityVOPages!=null && entityVOPages.getSize()>0) {
            List<KfWikiVO> entityVOS = entityVOPages.getRecords();
            if(Collections3.isNotEmpty(entityVOS)) {
                List<Long> ids = entityVOS.stream().map(KfWikiVO::getId).collect(Collectors.toList());
                CopAttachementQuery attachementQuery = new CopAttachementQuery();
                attachementQuery.setMessageIds(ids);
                List<CopAttachementVO> copAttachementVOS = copAttachementServiceImpl.list(attachementQuery);
                Map<Long, CopAttachementVO> copAttachementMap = Collections3.isNotEmpty(copAttachementVOS) ? copAttachementVOS.stream().collect(Collectors.toMap(CopAttachementVO::getMessageId, x -> x, (o, n) -> n)) : null;

                entityVOPages.getRecords().forEach(f -> {
                    f.setMarkCommonName(DefaultEnum.getDescByValue(f.getMarkCommon()));
                    f.setStatusDesc(PublishStatusEnum.getName(f.getStatus()));
                    f.setSyncStatusDesc(SyncStatusEnum.getName(f.getSyncStatus()));
                    CopAttachementVO copAttachementVO = copAttachementMap!=null && copAttachementMap.size()>0?copAttachementMap.get(f.getId()):null;
                    if(copAttachementVO!=null){
                        List<UniAttachVO> uniAttachVOS = copAttachementServiceImpl.transerCopAttachementToUniAttachement(copAttachementVO);
                        f.setAttachements(uniAttachVOS);
                    }
                });
            }
        }
        return entityVOPages;
    }

    @Override
    public List<KfWikiVO> listMarkCommon() {
        KfWikiQuery query = new KfWikiQuery();
        query.setMarkCommon(1);
        return this.getBean().list(query);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(KfWikiParam param) {
        KfWikiDO entityDO = BeanUtil.convertBean(param, KfWikiDO.class);
        Long id = GenerateId.generateId();
        entityDO.setId(id);
        entityDO.setSyncStatus(SyncStatusEnum.SYNC_NO.getValue());
        entityDO.setStatus(PublishStatusEnum.DISABLE.getValue());
        entityDO.setCreateBy(UserUtils.getUserId());
        entityDO.setCreateTime(LocalDateTime.now());
        entityDO.setModifyTime(LocalDateTime.now());
        List<UniAttachParam> uniAttachParams = param.getAttachements();
        if(Collections3.isNotEmpty(uniAttachParams)){
            CopAttachementParam copAttachementParam = copAttachementServiceImpl.transerUniAttachementToCopAttachement(uniAttachParams);
            if(copAttachementParam!=null){
                copAttachementParam.setMessageId(id);
                copAttachementServiceImpl.add(copAttachementParam);
            }
        }
        return kfWikiMapper.insert(entityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean modify(KfWikiParam param) {
        KfWikiDO entityDO = BeanUtil.convertBean(param, KfWikiDO.class);
        entityDO.setModifyBy(UserUtils.getUserId());
        entityDO.setModifyTime(LocalDateTime.now());
        entityDO.setSyncStatus(SyncStatusEnum.SYNC_NO.getValue());
        List<UniAttachParam> uniAttachParams = param.getAttachements();
        if(Collections3.isNotEmpty(uniAttachParams)){
            CopAttachementParam copAttachementParam = copAttachementServiceImpl.transerUniAttachementToCopAttachement(uniAttachParams);
            if(copAttachementParam!=null){
                copAttachementParam.setMessageId(entityDO.getId());
                copAttachementServiceImpl.modify(copAttachementParam);
            }
        }
        return kfWikiMapper.updateById(entityDO) > 0;
    }

    @Override
    public KfWikiVO view(Long id) {
        KfWikiDO entityDO = kfWikiMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        KfWikiVO entityVO = BeanUtil.convertBean(entityDO, KfWikiVO.class);
        if(entityVO != null) {
            entityVO.setMarkCommonName(DefaultEnum.getDescByValue(entityDO.getMarkCommon()));
            entityVO.setStatusDesc(PublishStatusEnum.getName(entityDO.getStatus()));
            entityVO.setSyncStatusDesc(SyncStatusEnum.getName(entityDO.getSyncStatus()));
            CopAttachementVO copAttachementVO = copAttachementServiceImpl.queryByMessageId(id);
            if(null != copAttachementVO) {
                List<UniAttachVO> uniAttachVOS = copAttachementServiceImpl.transerCopAttachementToUniAttachement(copAttachementVO);
                entityVO.setAttachements(uniAttachVOS);
            }
        }
        return entityVO;
    }
    @Override
    public Integer summaryCount(Long groupId){
        if(groupId==1L) groupId = null;
        return kfWikiMapper.selectCount(new LambdaQueryWrapper<KfWikiDO>().eq(KfWikiDO::getGroupId, groupId).eq(KfWikiDO::getDelStatus,0));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeStatus(Long id, Integer status) {
        KfWikiDO entityDO = kfWikiMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        entityDO.setStatus(status);
        entityDO.setModifyBy(UserUtils.getUserId());
        entityDO.setModifyTime(LocalDateTime.now());
        return kfWikiMapper.updateById(entityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean del(Long id) {
        KfWikiDO entityDO = kfWikiMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        return kfWikiMapper.deleteById(id) > 0;
    }

    private IKfWikiService getBean(){
        return SpringBeanUtil.getBean(KfWikiServiceImpl.class);
    }
}
